// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BatchCommandGroup.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework.CommandGroups
{
    #region Using Directives

    using System;
    using System.Collections.Generic;
    using System.IO;

    using Org.OpenTrader.Framework.CommandLine;

    #endregion

    /// <summary>
    /// The execution context command group.
    /// </summary>
    public class BatchCommandGroup : CommandGroup
    {
        #region Constants and Fields

        /// <summary>
        /// The commands.
        /// </summary>
        private readonly IDictionary<string, Command> commands;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="BatchCommandGroup"/> class.
        /// </summary>
        public BatchCommandGroup()
        {
            this.commands = new Dictionary<string, Command>();

            Command cmd;

            cmd = new RunCommand(this);
            this.commands[cmd.Name] = cmd;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets Commands.
        /// </summary>
        public override IDictionary<string, Command> Commands
        {
            get
            {
                return this.commands;
            }
        }

        /// <summary>
        /// Gets Help.
        /// </summary>
        public override string Help
        {
            get
            {
                return "This command group is used to handle batch scripts";
            }
        }

        /// <summary>
        /// Gets Name.
        /// </summary>
        public override string Name
        {
            get
            {
                return "batch";
            }
        }

        #endregion

        /// <summary>
        /// The run command.
        /// </summary>
        public class RunCommand : Command
        {
            #region Constants and Fields

            /// <summary>
            /// The identity.
            /// </summary>
            private static readonly Identity Identity = Identity.Create(System.Reflection.MethodBase.GetCurrentMethod());

            #endregion

            #region Constructors and Destructors

            /// <summary>
            /// Initializes a new instance of the <see cref="RunCommand"/> class.
            /// </summary>
            /// <param name="commandGroup">
            /// The command group.
            /// </param>
            public RunCommand(CommandGroup commandGroup)
                : base(commandGroup)
            {
            }

            #endregion

            #region Properties

            /// <summary>
            /// Gets Help.
            /// </summary>
            public override string Help
            {
                get
                {
                    return "run the given command file";
                }
            }

            /// <summary>
            /// Gets Name.
            /// </summary>
            public override string Name
            {
                get
                {
                    return "run";
                }
            }

            /// <summary>
            /// Gets Usage.
            /// </summary>
            public override string Usage
            {
                get
                {
                    return string.Format("{0} {1} command_file", this.CommandGroup.Name, this.Name);
                }
            }

            #endregion

            #region Public Methods

            /// <summary>
            /// The execute.
            /// </summary>
            /// <param name="args">
            /// The args.
            /// </param>
            /// <returns>
            /// </returns>
            public override Status Execute(string[] args)
            {
                if (args.Length < 1)
                {
                    return Status.Failure(Identity, "parameter command_file is missing");
                }

                var filename = args[0];

                // The given parameters (if any)
                var parametersCount = Math.Max(0, args.Length - 1);
                var parameters = new string[] { };
                if (parametersCount > 0)
                {
                    parameters = new string[parametersCount];
                    Array.Copy(args, 1, parameters, 0, parametersCount);
                }

                IDictionary<string, string> variables = new Dictionary<string, string>();

                foreach (var assignment in parameters)
                {
                    var couple = assignment.Split(new[] { '=' });
                    var key = couple[0];
                    var value = couple[1];
                    variables[key] = value;
                }

                using (var sr = new StreamReader(filename))
                {
                    string s;
                    do
                    {
                        read:

                        // Read command
                        s = sr.ReadLine();

                        // Eof
                        if (s == null)
                        {
                            break;
                        }

                        // newlines and comments
                        if (s.Length == 0 || s.StartsWith("#"))
                        {
                            goto read;
                        }

                        // Replace variables by their values
                        foreach (var va in variables.Keys)
                        {
                            s = s.Replace("$" + va, variables[va]);
                        }

                        // Split to create an array similar to the one passed to Main(...)
                        var arguments = s.Split(new[] { ' ' });

                        if (arguments.Length > 0)
                        {
                            try
                            {
                                // logger.Log(ELogLevel.Info, string.Format("Executing \"{0}\"", s));
                                Console.WriteLine(string.Format("Executing \"{0}\"", s));
                                CommandLine.Process(arguments);
                            }
                            catch
                            {
                                Console.WriteLine(string.Format("Error while executing {0}", s));

                                // logger.Log(ELogLevel.Info, );
                            }
                        }
                    }
                    while (s != null);
                }

                return Status.Success(Identity);
            }

            #endregion
        }
    }
}